package com.ssmeasy.jdgl.serviceImpl;

import com.ssmeasy.jdgl.dao.OrdersMapper;
import com.ssmeasy.jdgl.dao.RoomMapper;
import com.ssmeasy.jdgl.pojo.Orders;
import com.ssmeasy.jdgl.pojo.Room;
import com.ssmeasy.jdgl.service.OrdersService;
import com.ssmeasy.jdgl.utils.SStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private RoomMapper roomMapper;

    /**
     * 添加订单，开房
     *
     * @param id
     * @param name
     * @param idcard
     */
    @Transactional
    @Override
    public void openRoom(int id, String name, String idcard) throws Exception {


        //参数判空(用户名不能为空，idcard必须为正确的身份证号码格式)
        if (StringUtils.isEmpty(name) || !SStringUtils.isIDNumber(idcard)) {
            throw new Exception("入住信息不对");
        }

        //先查询房间信息
        Room room = roomMapper.selectByPrimaryKey(id);

        //如果房间不存在，或者房间已经被定
        if(room == null || room.getStatus() == 1)
            throw new Exception("无法开房");

        //创建订单
        Orders order = new Orders();
        order.setRoomid(id);
        order.setName(name);
        order.setIdcard(idcard);
        SimpleDateFormat sd = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
        order.setStarttime(sd.format(new Date()));
        order.setEndtime("none");

        //插入
        ordersMapper.insert(order);

        //修改房间状态
        room.setStatus(1);
        roomMapper.updateByPrimaryKey(room);

    }

    /**
     * 删除订单，退房
     *
     * @param id
     */
    @Transactional
    @Override
    public void exitRoom(int id) throws Exception {
        //先获取房间信息
        Room room = roomMapper.selectByPrimaryKey(id);


        //如果房间不存在，或者房间空闲
        if(room == null || room.getStatus() == 0)
            throw new Exception("无法退房");


        //获取当前房间最后一个还未退房的订单信息
        Orders order = ordersMapper.selectByRoomIdAndNoEnd(id);

        if(order == null)
            throw new Exception("没有订单信息");

        //设置退房时间
        SimpleDateFormat sd = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
        order.setEndtime(sd.format(new Date()));

        //更新订单信息
        ordersMapper.updateByPrimaryKey(order);


        //修改房间状态
        room.setStatus(0);
        roomMapper.updateByPrimaryKey(room);

    }
}
